//
//  LBContactListViewController.m
//  LBContactListViewController
//
//  Created by LINAICAI on 2017/12/6.
//

#import "LBContactListViewController.h"
#import "LBAddContactViewController.h"
#import "LBContactViewController.h"
#import "LBContactModel.h"
#import <Masonry.h>
#import "LBContactCell.h"
#import <LBCoreKit.h>
#import <LBUIKit.h>
#import <LBLoadingView.h>
#import <UIScrollView+LBRefreshAndMoreTableView.h>
#import "LBContactManager.h"
#import <MJExtension.h>
#import <LBAlert.h>
#import "LBInviteContactsNodataView.h"
#import "LBPhoneInviteView.h"

static NSString *cellID = @"LBContactCell";
@interface LBContactListViewController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic , strong)UIBarButtonItem *addContactBarButtonItem;
///分组KEY
@property (nonatomic , strong)NSArray *heads;
///传入的预选中的联系人
@property (nonatomic , strong)NSArray<NSString *> *numbers;
///当前选中的联系人(手机号码)
@property (nonatomic , strong)NSMutableArray<NSString *> *currentNumbers;
///列表控件
@property (nonatomic , strong)UITableView *tableView;
///空数据视图
@property (nonatomic , strong)LBInviteContactsNodataView *nodataView;
///遮罩
@property (nonatomic , strong)UIView *accessoryView;
///搜索控件
@property (nonatomic , strong)UISearchBar *searchBar;
///模式
@property (nonatomic , assign)LBContactListViewMode mode;
///列表展示的数据源
@property (nonatomic , strong)NSMutableArray<NSMutableArray<LBContactModel*>*> *dataSources;
///服务端获取的远程数据
@property (nonatomic , strong)NSArray<LBContactModel *> *remoteDataSources;
///模糊搜索结果
@property (nonatomic , strong)NSArray<LBContactModel *> *searchResultDataSources;
@end

@implementation LBContactListViewController
#pragma mark- init
- (instancetype)init
{
    self = [super init];
    if (self) {
        _mode = LBContactListViewModeNomal;
        _numbers = nil;
        _delegate = self;
    }
    return self;
}
///构造函数
- (instancetype)initWithSelectMode:(LBContactListViewMode)selectMode{
    return [self initWithSelectMode:selectMode numbers:nil];
}
///构造函数，需要传递选中的联系人id
- (instancetype)initWithSelectMode:(LBContactListViewMode)selectMode numbers:(NSArray<NSString *> *)numbers{
    self = [super init];
    if (self) {
        _mode = selectMode;
        _numbers = numbers;
        _delegate = self;
    }
    return self;
}
#pragma mark- Getting|Setting
- (NSArray<NSString *> *)numbers{
    if (!_numbers) {
        _numbers = [[NSArray<NSString *> alloc]init];
    }
    return _numbers;
}
- (NSArray<LBContactModel *> *)searchResultDataSources{
    if (!_searchResultDataSources) {
        _searchResultDataSources = [[NSArray<LBContactModel *> alloc]init];
    }
    return _searchResultDataSources;
}
- (NSArray<LBContactModel *> *)remoteDataSources{
    if (!_remoteDataSources) {
        _remoteDataSources = [[NSArray<LBContactModel *> alloc]init];
    }
    return _remoteDataSources;
}
- (NSArray *)heads{
    if (!_heads) {
        _heads = @[@"其他",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",
                   @"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",
                   @"U",@"V",@"W",@"X",@"Y",@"Z"];
    }
    return _heads;
}
- (NSMutableArray<LBContactModel*> *)array{
    return [NSMutableArray<LBContactModel*> new];
}
- (NSMutableArray<NSMutableArray<LBContactModel*>*> *)dataSources{
    if (!_dataSources) {
        _dataSources = [NSMutableArray<NSMutableArray<LBContactModel*>*> new];
        for (NSInteger i = 0; i<self.heads.count; i++) {
            [_dataSources addObject:[self array]];
        }
    }
    return _dataSources;
}
- (LBInviteContactsNodataView *)nodataView {
    if (!_nodataView) {
        _nodataView = [[LBInviteContactsNodataView alloc] init];
        [_nodataView setBlock:^{
            LBPhoneInviteView *inviteView = [[LBPhoneInviteView alloc]init];
            [LBAlert showCustom:inviteView title:@"手机号直邀" buttons:@[@"取消",@"确定"] block:^(NSInteger answer) {
                
                
            } hasCloseButton:NO];
        }];
    }
    return _nodataView;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.sectionIndexBackgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [UIView new];
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_tableView registerClass:[LBContactCell class] forCellReuseIdentifier:cellID];
        
    }
    return _tableView;
}

- (UISearchBar *)searchBar{
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc]initWithFrame:CGRectZero];
        _searchBar.placeholder=@"搜索联系人";
        [_searchBar setBackgroundColor:[UIColor whiteColor]];
        _searchBar.searchBarStyle = UISearchBarStyleMinimal;
        [_searchBar.layer setCornerRadius:2];
        [_searchBar.layer setMasksToBounds:YES];
        [_searchBar setDelegate:(id<UISearchBarDelegate> _Nullable)self];
        [_searchBar setSearchTextPositionAdjustment:UIOffsetMake(9, 0)];
        [_searchBar setSearchFieldBackgroundPositionAdjustment:UIOffsetMake(5, 0)];
        [_searchBar setTextContentType:UITextContentTypeTelephoneNumber];
        UITextField *searchField = [_searchBar valueForKey:@"_searchField"];
        // 输入文本颜色
        searchField.textColor = [UIColor darkBlack];
        // 默认文本颜色
        [searchField setValue:[UIColor black] forKeyPath:@"_placeholderLabel.textColor"];
        [searchField setValue:[UIFont systemFontOfSize:13.5] forKeyPath:@"_placeholderLabel.font"];
        
    }
    return _searchBar;
}
- (UIBarButtonItem *)addContactBarButtonItem{
    if (!_addContactBarButtonItem) {
        _addContactBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"LBContactListViewController.bundle/lb_user_contact_add"] style:UIBarButtonItemStylePlain target:self action:@selector(addContactClick:)];
    }
    return _addContactBarButtonItem;
}
#pragma mark- LifeCycle
- (void)dealloc{
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self.searchBar setSearchFieldBackgroundImage:[UIImage GetImageFromColor: [UIColor whiteColor] rect:self.searchBar.bounds] forState:UIControlStateNormal];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = LBCOLOR(243, 246, 249);
    self.navigationItem.rightBarButtonItem = self.addContactBarButtonItem;
    
    [self.view addSubview:self.searchBar];
    [self.view addSubview:self.tableView];
    
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).mas_offset(10);
        make.right.mas_equalTo(self.view.mas_right).mas_offset(-10);
        make.top.mas_equalTo(self.view.mas_top).mas_offset(10);
        make.height.mas_equalTo(32);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.mas_equalTo(self.view.mas_top).mas_offset(52);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    WS(ws);
    [self.tableView addRefreshAction:^{
        [ws requestData];
    } loadMoreAction:NULL];
    
    [self requestData];
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    ///设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    ///将触摸事件添加到当前view
    [self.view addGestureRecognizer:tapGestureRecognizer];
}
- (void)addContactClick:(id)sender{
    LBAddContactViewController *vc = [[LBAddContactViewController alloc]init];
    vc.title = @"添加联系人";
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark- Delegate
- (void)LBContactListViewControllerSelectChangeWithContact:(LBContactModel*)contact{
    NSLog(@"LBContactListViewControllerSelectChangeWithContact");
}
- (void)LBContactListViewControllerDidSelectWithContact:(LBContactModel*)contact{
    NSLog(@"LBContactListViewControllerDidSelectWithContact");
    LBContactViewController *vc = [[LBContactViewController alloc]initWithModel:contact canEditing:YES];
    [self.navigationController pushViewController:vc animated:YES];
}
//开始搜索联系人
- (void)LBContactListViewDidBegainSearchContact{
    NSLog(@"LBContactListViewDidBegainSearchContact");
}
//结束搜索联系人
- (void)LBContactListViewDidEndSearchContact{
    NSLog(@"LBContactListViewDidEndSearchContact");
}
//每次搜索到的结果，返回联系人模型数组
- (void)LBContactListViewSearchResultWithContacts:(NSArray<LBContactModel*> *)contacts{
    NSLog(@"LBContactListViewSearchResultWithContacts");
    NSLog(@"search = %@",contacts);
}
#pragma mark- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    LBContactModel *model = self.dataSources[indexPath.section][indexPath.row];
    switch (self.mode) {
            case LBContactListViewModeNomal:
            {
                ///浏览模式
                if (self.delegate && [self.delegate respondsToSelector:@selector(LBContactListViewControllerDidSelectWithContact:)]) {
                    [self.delegate LBContactListViewControllerDidSelectWithContact:model];
                }
            }
            break;
            case LBContactListViewModeSingleSelect:
            {
                ///单选模式
                if ([self.currentNumbers containsObject:model.mobilePhone]) {
                    ///取消选中
                    NSMutableArray *array = [NSMutableArray arrayWithArray:@[model.mobilePhone]];
                    [array removeObject:model.mobilePhone];
                    self.currentNumbers = array;
                }
                else{
                    ///选中
                    NSMutableArray *array = [NSMutableArray arrayWithArray:@[model.mobilePhone]];
                    [array addObject:model.mobilePhone];
                    self.currentNumbers = array;
                }
                [tableView reloadData];
            
            }
            break;
            case LBContactListViewModeMultiSelect:///多选模式
            case LBContactListViewModeSelected:///已选模式
            {
                if ([self.currentNumbers containsObject:model.mobilePhone]) {
                    //删除
                    NSMutableArray *array = [NSMutableArray arrayWithArray:self.currentNumbers];
                    [array removeObject:model.mobilePhone];
                    self.currentNumbers = array;
                }
                else{
                    //新增
                    NSMutableArray *array = [NSMutableArray arrayWithArray:self.currentNumbers];
                    [array addObject:model.mobilePhone];
                    self.currentNumbers = array;
                }
                [tableView reloadData];
            }
            break;
        default:
            break;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 75;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (!self.dataSources[section].count) {
        return 0;
    }
    return 35;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.heads.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataSources[section] count];
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 35)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, view.bounds.size.width-20, view.bounds.size.height)];
    label.text = self.heads[section];
    label.textColor = [UIColor darkBlack];
    label.font = LBFONT(18);
    [view addSubview:label];
    return view;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LBContactCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    LBContactModel *model = self.dataSources[indexPath.section][indexPath.row];
    [cell setCellWithModel:model indexPath:indexPath];
    //如果是浏览模式
    if (_mode == LBContactListViewModeNomal ) {
        [cell.selectButton setHidden:YES];
    }
    else{
        [cell.selectButton setHidden:NO];
    }
    //如果刚好选中该联系人
    if ([self.currentNumbers containsObject:model.mobilePhone]) {
        [cell.selectButton setSelected:YES];
    }
    else{
        [cell.selectButton setSelected:NO];
    }
    
    return cell;
    
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPat{
    //浏览模式下才能删除联系人
    if (_mode == LBContactListViewModeNomal) {
        return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleNone;
}
//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
//进入编辑模式，按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete){
        //删除模式
        WS(weakSelf);
        __weak LBContactModel *model = self.dataSources[indexPath.section][indexPath.row];
        NSArray *array = [NSArray arrayWithObjects:model.id, nil];
        [LBContactManager deleteContactWithIds:[array mj_JSONObject] success:^(NSString *message) {
            [LBAlert say:^(NSInteger answer){
                [weakSelf.dataSources[indexPath.section] removeObject:model];
                [tableView reloadData];
            } message:@"删除成功"];
            
        } fail:^(NSString *message) {
            [LBAlert say:message];
        }];
    }
}
#pragma mark- UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    if (self.delegate && [self.delegate respondsToSelector:@selector(LBContactListViewControllerDidBegainSearchContact)]) {
        [self.delegate LBContactListViewControllerDidBegainSearchContact];
    }
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    if (self.delegate && [self.delegate respondsToSelector:@selector(LBContactListViewControllerDidEndSearchContact)]) {
        [self.delegate LBContactListViewControllerDidEndSearchContact];
    }
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self closeSearchMode];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if ([searchText length]==0) {
        //如果输入为空，自动关闭搜索列表，展示全部服务器数据
        [self closeSearchMode];
        if (self.delegate && [self.delegate respondsToSelector:@selector(LBContactListViewControllerCleanAllSearchContact)]) {
            [self.delegate LBContactListViewControllerCleanAllSearchContact];
        }
    }
    else{
        //开始搜索
        [self enterSearchModeWithkeyword:searchText];
    }
}
#pragma mark- Private
//获取汉字拼音(传入汉字字符串, 返回小写拼音)
- (NSString *)getPinYin:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pinYin = [str lowercaseString];
    
    //获取并返回，过滤所有空格符号
    return [pinYin stringByReplacingOccurrencesOfString:@" " withString:@""];
}
//进入搜索模式，展示搜索数据
- (void)enterSearchModeWithkeyword:(NSString *)keyword{
    NSMutableArray *results = [NSMutableArray new];
    for (LBContactModel *model in self.remoteDataSources) {
        if ([[model.pingYin lowercaseString] containsString:[self getPinYin:keyword]] ||
            [[model.mobilePhone lowercaseString] containsString:keyword]) {
            [results addObject:model];
        }
    }
    //给搜索结果数组赋值
    self.searchResultDataSources = results;
    //处理结果数据给展示列表数据源
    [self getData:results];
    //回调搜索结果
    if (self.delegate && [self.delegate respondsToSelector:@selector(LBContactListViewControllerSearchResultWithContacts:)]) {
        [self.delegate LBContactListViewControllerSearchResultWithContacts:results];
    }
    [self.tableView lb_setCustomView:self.nodataView];
    [self.tableView reloadData];
}
//退出搜索模式，展示全部远程数据
- (void)closeSearchMode{
    [self.searchBar resignFirstResponder];
    [self getData:self.remoteDataSources];
    [self.tableView lb_setEmptyNoData:@"暂无联系人"];
    [self.tableView reloadData];
}
- (void)requestData{
    [LBLoadingView showInView:self.view];
    WS(ws);
    [LBContactManager searchContactWithCondition:@"" success:^(NSArray<LBContactModel *> *models) {
        ws.remoteDataSources = models;
        [ws getData:models];
        [ws.tableView lb_setEmptyNoData:@"暂无联系人" reloadBlock:^{
            [self requestData];
        }];
        successToRefresh(ws.tableView)
        
    } fail:^(NSString *message) {
        failToRefresh(ws.tableView, message)
    }];
    
}
- (void)getData:(NSArray<LBContactModel*> *)array{
    //每次拿到服务器查询返回的数据，都要重新设置下当前所有选中的数据，除非当前已经有选中的项目了，就不重新设置
    if (!self.currentNumbers.count) {
        self.currentNumbers = [NSMutableArray arrayWithArray:self.numbers];
    }
    //清除旧数据
    for (NSMutableArray *array in self.dataSources) {
        [array removeAllObjects];
    }
    
    
    for (LBContactModel *model in array) {
        //如果是已选模式，要过滤相关的已选项
        if (self.mode == LBContactListViewModeSelected) {
            if ([self.numbers containsObject:model.mobilePhone]) {
                continue;
            }
        }
        //如果首字母是英文字母里面的
        if ([self.heads containsObject:model.firstupper]) {
            NSInteger index = [self.heads indexOfObject:model.firstupper];
            [self.dataSources[index] addObject:model];
        }
        else{
            //首字母不是英文字母
            [self.dataSources[0] addObject:model];
        }
        
        
    }
    
}
-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [self.searchBar resignFirstResponder];
}
#pragma mark- Public
///获取所有当前的联系人
- (NSArray<LBContactModel*> *)AllContacts{
    NSMutableArray *result = [NSMutableArray new];
    for (LBContactModel *model in self.remoteDataSources) {
        [result addObject:model];
    }
    return result;
}
///获取所有选中的联系人
- (NSArray<LBContactModel*> *)AllSelectContacts{
    NSMutableArray *result = [NSMutableArray new];
    for (LBContactModel *model in self.remoteDataSources) {
        if (_mode == LBContactListViewModeSelected) {
            //选中模式下
            if ([self.currentNumbers containsObject:model.mobilePhone] && ![self.numbers containsObject:model.mobilePhone]) {
                [result addObject:model];
            }
        }
        else{
            if ([self.currentNumbers containsObject:model.mobilePhone]) {
                [result addObject:model];
            }
        }
        
    }
    return result;
}
@end
